package jhr.cms.service.impl;

import java.io.Serializable;
import java.util.List;

import jhr.cms.dao.UserDao;
import jhr.cms.domain.ServiceException;
import jhr.cms.domain.User;
import jhr.cms.service.UserServiceIF;

public class UserService implements UserServiceIF {
	private UserDao userDao;
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public User save(User u) throws ServiceException {
		if(u == null || u.getName() == null || u.getPassword() == null)
			throw new ServiceException("用户不能为空！");
		try{
			userDao.saveOrUpdate(u);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
		return u;
	}

	@Override
	public User update(User u) throws ServiceException {
		if(u == null || u.getName() == null || u.getPassword() == null)
			throw new ServiceException("用户不能为空！");
		try{
			userDao.saveOrUpdate(u);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
		return u;
	}

	@Override
	public void delete(User u) throws ServiceException {
		if(u == null||u.getId() == null)
			throw new ServiceException("用户不能为空！");
		try{
			userDao.delete(u.getId());
		}catch (Exception e) {
			throw new ServiceException(e);
		}

	}

	@Override
	public void delete(Serializable id) throws ServiceException {
		if(id == null)
			throw new ServiceException("用户Id不能为空！");
		try{
			userDao.delete(id);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public User get(Serializable id) throws ServiceException {
		if(id == null)
			throw new ServiceException("用户Id不能为空！");
		try{
			return userDao.get(id);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public User login(String name, String password) throws ServiceException {
		if(name == null || password == null)
			throw new ServiceException("用户名和密码不能为空！");
		try{
			List<User> list = userDao.find(
					"from User where name=? and password=?", 0, 1, name, password);
			if(list.size() == 1)
				return list.get(0);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
		return null;
	}

	@Override
	public List<User> find(String hql, int start, int size, Object... args) throws ServiceException {
		if(hql == null || start<0 || size<1)
			throw new ServiceException("查询条件不能为空！");
		return userDao.find(hql, start, size, args);
	}

}
